package com.jd.pet.service.impl;

import com.jd.basic.exception.BusinessException;
import com.jd.basic.service.IBaiduAiAuditService;
import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.*;
import com.jd.order.domain.OrderPetAcquisition;
import com.jd.order.mapper.OrderPetAcquisitionMapper;
import com.jd.org.domain.Employee;
import com.jd.org.domain.Shop;
import com.jd.org.mapper.EmpMapper;
import com.jd.org.mapper.ShopMapper;
import com.jd.pet.domain.Pet;
import com.jd.pet.domain.SearchMasterMsg;
import com.jd.pet.domain.SearchMasterMsgAuditLog;
import com.jd.pet.mapper.PetMapper;
import com.jd.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.jd.pet.mapper.SearchMasterMsgMapper;
import com.jd.pet.query.SearchMasterMsgQuery;
import com.jd.pet.service.ISearchMasterMsgService;
import com.jd.user.domain.Logininfo;
import com.jd.user.domain.User;
import com.jd.user.mapper.UserMapper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Value("${rocketmq.producer.send-message-timeout}")
    private Integer msgTime;
    @Override
    public AjaxsResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        //1.获取登录人id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        msg.setUserId(user.getId());
        //2.将信息存入数据库，避免审核失败重新填写
        searchMasterMsgMapper.save(msg);
        //3.百度审核
        Boolean boo1 = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());//审核文本内容
        Boolean boo2 = baiduAiAuditService.imageAudit(msg.getResources());//审核图片
        if (boo1 && boo2){//都为true成功
            // 修改状态
            msg.setState(1);// 1为审核通过，等待店铺接单
            // 获取店铺
            List<Shop> shops = shopMapper.loadAll();
            // 用户发布寻主的地址
            Point point = DistanceUtils.getPoint(msg.getAddress());
            // 寻找附近店铺地址
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            // 判断是否找到附近店铺
            if (nearestShop!=null){// 找到附近店铺添加
                msg.setShopId(nearestShop.getId());
            }
            // 先更新数据库再发短信，避免数据库上传失败
            searchMasterMsgMapper.update(msg);
            // 修改审核成功的日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(1);
            log.setNote("审核通过");
            searchMasterMsgAuditLogMapper.save(log);
            //发送短信给店铺管理员
            if (nearestShop!=null){
                Employee employee = empMapper.loadByShopId(nearestShop.getId());
                System.out.println("你有新的订单"+msg.getAddress()+"请接");
            }
            return new AjaxsResult();
        }else {
            // 修改审核失败的日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);
            System.out.println("你的审核未通过，请重新修改");
            return AjaxsResult.me().setSuccess(false).setMsg("审核失败");
        }
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //判断店铺管理员和平台管理员
        // 获取管理员信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = empMapper.loadByLogininfoId(logininfo.getId());
        // 根据shopid判断店铺管理员和平台管理员
        if (employee.getShop_id()!=null){//为店铺管理人员
            query.setShopId(employee.getShop_id());//添加到分页
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 获取user对象
        // 通过过登录人信息获取
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        // 将用户id设置到分页
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public void reject(Long msgId) {
        searchMasterMsgMapper.reject(msgId);
    }

    @Override
    public void accept(Map<String, String> map) {
        //接收前端传来的参数
        long msgId = Long.parseLong(map.get("msgId"));
        long empId = Long.parseLong(map.get("handler"));
        String note = map.get("note");
        //1.校验当前订单是否已经处理
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(msgId);
        if (order!=null){//说明正在处理寻找
            throw new BusinessException("订单正在处理，请等待");

        }
        //2.通过寻主id获取宠物对象，添加到系统
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = msg2Pet(msg);
        petMapper.save(pet);
        //3.订单生成
        OrderPetAcquisition orderTem = buildOrderPetAcquisition(msg,pet,empId,note);
        orderPetAcquisitionMapper.save(orderTem);
        rocketMQTemplate.syncSend("producer-topic",
                MessageBuilder.withPayload(orderTem.getId()).build(),msgTime,3);
        //4.发短信通知，上门取货
        //Employee employee = employeeMapper.loadById(empId);
        //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请及时处理，地址："+msg.getAddress());
        System.out.println("你有新的订单，请及时处理，地址："+msg.getAddress());
    }

    private OrderPetAcquisition buildOrderPetAcquisition(SearchMasterMsg msg, Pet pet, long empId, String note) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        //生成唯一订单号
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(msg.getName()+"收购订单");
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 1000*60*60*24*2));
        order.setState(0);//待处理
        order.setPrice(msg.getPrice());
        //        order.setPaytype(); //现金支付
        order.setPetId(pet.getId());
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());
        return order;

    }

    private Pet msg2Pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setState(0);
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }
}
